'use strict';

const Controller = require('egg').Controller;
const moment = require('moment');

class ApisController extends Controller {
  /**
   *
   * @api {get} /banners 轮播图获取
   * @apiName banners
   * @apiGroup banners
   * @apiVersion  1.0.0
   *
   *
   *
   * @apiSuccess (200) {Number} status 状态码
   * @apiSuccess (200) {String} url banner图
   * @apiSuccess (200) {String} link 跳转的咨询id
   * @apiSuccess (200) {String} weight 权重
   *
   *
   *
   * @apiSuccessExample {type} Success-Response:
   * {
   *     status : 0 ,
   *     message: [
   *       {
   *          url:'base64:XXX',
   *          link:'b3dasdwqdjio2',
   *          weight:100
   *        }
   *     ]
   * }
   *
   *
   */
  async banners() {
    try {
      const bannerList = await this.ctx.model.Banner.find({}).sort({ weight: -1 });
      this.ctx.body = { status: 0, message: bannerList };
    } catch (e) {
      this.ctx.body = { status: -1, message: e };
    }
  }

  /**
   *
   * @api {get} /articles 资讯列表
   * @apiName articles
   * @apiGroup article
   * @apiVersion  1.0.0
   *
   *
   * @apiParam  {Number} [skip]  资讯数量偏移量
   * @apiParam  {Number} [limit]  资讯获取数量
   * @apiParam  {Boolean} [history]  是否查询往期资讯
   * @apiParam  {String} [title]  根据文章标题模糊搜索
   *
   * @apiSuccess (200) {Number} status 状态码
   * @apiSuccess (200) {Number} count 当前history/title搜索下的资讯总条数
   * @apiSuccess (200) {Object[]} data  当前资讯列表
   *
   * @apiParamExample  {Object} Request-Example:
   * {
   *     skip : 0,
   *     limit: 20,
   *     title: 哈哈
   * }
   *
   *
   * @apiSuccessExample {Object} Success-Response:
   * {
   *     status:0,
   *     message:{
   *      count : 120,
   *      data  : [{
   *        title:'标题',
   *        avatar:'封面图',
   *        createTime:'创建时间',
   *        history:'是否是往期资讯'
   *      }]
   *     }
   * }
   *
   *
   */
  async articles() {
    let { skip, limit, history, title } = this.ctx.request.query;
    skip = +skip || 0;
    limit = +limit || 9999;
    const query = {};
    if (history) {
      query.history = true;
    }
    if (title) {
      query.title = new RegExp(title, 'i');
    }
    const data = await this.ctx.model.Article.find(query, { content: 0 }).skip(skip).limit(limit);
    data.forEach((v, k) => {
      data[k] = v.toObject();
      data[k].createTime = moment(data[k].createTime).format('YYYY-MM-DD HH:mm');
    });
    const count = await this.ctx.model.Article.count(query);
    this.ctx.body = { status: 0, message: { data, count } };
  }
  /**
 *
 * @api {get} /projects 项目列表
 * @apiName projects
 * @apiGroup project
 * @apiVersion  1.0.0
 *
 *
 * @apiParam  {Number} [skip] 偏移量
 * @apiParam  {Number} [limit] 条数
 * @apiParam  {String} [title] 名称模糊搜索
 * @apiParam  {String} [userId] 用户标识
 * @apiParam  {Boolean} [vote] 是否根据voteCount排序
 *
 * @apiSuccess (200) {Number} status 状态码
 * @apiSuccess (200) {Number} count 总条数
 * @apiSuccess (200) {Object[]} data 项目信息
 *
 * @apiParamExample  {type} Request-Example:
 * {
 *     skip : 0,
 *     limit : 10,
 *     title : '奥特曼',
 *     userId:'dsad8wqd88aas'
 * }
 *
 *
 * @apiSuccessExample {type} Success-Response:
 * {
 *     status : 0,
 *     message:{
 *        count:100,
 *        data:[
 *          {
 *             title:'标题',
 *             avatar:'封面',
 *             voteCount:'点赞数',
 *             hasVote:false,
 *             seq:1
 *          }
 *        ]
 *     }
 * }
 *
 *
 */
  async projects() {
    let { skip, limit, title, userId, vote } = this.ctx.request.query;
    skip = +skip || 0;
    limit = +limit || 9999;
    const query = {};
    let voteProject;
    if (title) {
      query.title = new RegExp(title, 'i');
    }
    if (userId) {
      const voteData = await this.ctx.model.Vote.findOne({ userId }).sort({ createTime: -1 });
      if (moment(voteData).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')) {
        voteProject = voteData._id;
      }
    }
    let data;
    if (vote) {
      data = await this.ctx.model.Project.find(query, { content: 0 }).skip(skip).limit(limit)
        .sort({ voteCount: -1 });
    } else {
      data = await this.ctx.model.Project.find(query, { content: 0 }).skip(skip).limit(limit);
    }
    data.forEach((v, k) => {
      data[k] = data[k].toObject();
      if (v._id === voteProject) {
        data[k].hasVote = true;
      } else {
        data[k].hasVote = false;
      }
      data[k].createTime = moment(data[k].createTime).format('YYYY-MM-DD HH:mm');
    });
    const count = await this.ctx.model.Project.count(query);
    this.ctx.body = { status: 0, message: { data, count } };
  }

  /**
   *
   * @api {get} /articleDetail 咨询详情
   * @apiName articleDetail
   * @apiGroup article
   * @apiVersion  1.0.0
   *
   *
   * @apiParam  {String} id 资讯id
   *
   * @apiSuccess (200) {Number} status 状态码
   * @apiSuccess (200) {Object} message 咨询详情
   *
   * @apiParamExample  {Object} Request-Example:
   * {
   *     id : 'd56dwad87wd65awad'
   * }
   *
   *
   * @apiSuccessExample {Object} Success-Response:
   * {
   *     status : 0,
   *     message:{
   *        title:'标题',
   *        content:'内容',
   *        createTime:'上传时间',
   *        avatar:'封面'
   *     }
   * }
   *
   *
   */
  async articleDetail() {
    const { id } = this.ctx.request.query;
    if (!id) {
      this.ctx.body = { status: -1, message: 'id为空' };
      return;
    }
    const data = await this.ctx.model.Article.findOne({ _id: id });
    data.content = data.content.replace(/src\=\"/g, 'src="https://mmmagin.cn');
    this.ctx.body = { status: 0, message: data };
  }

  /**
 *
 * @api {get} /projectDetail 项目详情
 * @apiName projectDetail
 * @apiGroup project
 * @apiVersion  1.0.0
 *
 *
 * @apiParam  {String} id 项目id
 *
 * @apiSuccess (200) {Number} status 状态码
 *
 * @apiParamExample  {Object} Request-Example:
 * {
 *     id : 'd8wdq7dsd8w7q8dw8'
 * }
 *
 *
 * @apiSuccessExample {Object} Success-Response:
 * {
 *     status : 0,
 *     message:{
 *       title:'标题',
 *       content:'详情内容',
 *       avatar:'封面图',
 *       voteCount:'点赞数量',
 *       createTime:'创建时间'
 *     }
 * }
 *
 *
 */
  async projectDetail() {
    const { id } = this.ctx.request.query;
    if (!id) {
      this.ctx.body = { status: -1, message: 'id为空' };
      return;
    }
    const data = await this.ctx.model.Project.findOne({ _id: id });
    data.content = data.content.replace(/src\=\"/g, 'src="https://mmmagin.cn');
    this.ctx.body = { status: 0, message: data };
  }

  /**
   *
   * @api {get} /vote 投票
   * @apiName vote
   * @apiGroup vote
   * @apiVersion  1.0.0
   *
   *
   * @apiParam  {String} userId 用户唯一标示(随便是啥都行)
   * @apiParam  {String} projectId 项目id
   * @apiParam  {String} username 用户名
   * @apiParam  {String} headimg 用户头像
   *
   * @apiSuccess (200) {Number} status 状态码
   *
   * @apiParamExample  {type} Request-Example:
   * {
   *     userId : 'da89dwad98ad79ad',
   *     projectId : 'd9sadwq8dsaddas8sd',
   *     username : 'd9sadwq8dsaddas8sd',
   *     headimg : 'd9sadwq8dsaddas8sd',
   * }
   *
   *
   * @apiSuccessExample {Object} Success-Response:
   * {
   *     status : 0
   * }
   *
   *
   */
  async vote() {
    const { userId, projectId, username, headimg } = this.ctx.request.query;
    if (!(userId && projectId && username && headimg)) {
      this.ctx.body = { status: -1, message: 'userId或projectId缺失' };
      return;
    }
    const voteData = await this.ctx.model.Vote.findOne({ userId }).sort({ createTime: -1 });
    if (voteData) {
      if (moment(voteData.createTime).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')) {
        this.ctx.body = { status: 1, message: '今日已经投票过了' };
        return;
      }
    }
    await (new this.ctx.model.Vote({ userId, projectId, username, headimg, createTime: new Date() })).save();
    await this.ctx.model.Project.update({ _id: projectId }, { $inc: { voteCount: 1 } });
    this.ctx.body = { status: 0, message: '投票成功' };
  }

  async notification() {
    const data = await this.ctx.model.Notification.findOne({});
    this.ctx.body = { status: 0, message: data };

  }
}


module.exports = ApisController;
